﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using ESRI.ArcGIS.Geodatabase;
using BTGISWASECO.Core;

namespace BTGISWASECO.Data
{
    /// <summary>
    /// Builds the structure of a DataTable according to supplied fields
    /// </summary>
    public class DataTableBuilder
    {
        #region =========================== PRIVATE ===============================

        private List<IField> fields;
        public IFeatureClass featureClass;

        private DataColumn buildColumn(IField field)
        {
            DataColumn col = new DataColumn();
            col.ColumnName = field.AliasName;
            col.AllowDBNull = field.IsNullable;
            if (field.Domain != null)
                col.DataType = TypeConvertor.Convert(esriFieldType.esriFieldTypeString);
            else
                col.DataType = TypeConvertor.Convert(field.Type);
            return col;
        }

       
        private DataTable buildTable()
        {
            DataTable dataTable = new DataTable(featureClass.AliasName);
            DataColumnCollection colCollection = dataTable.Columns;
            foreach (IField f in fields)
            {
                if ((!f.Name.Equals("SHAPE")) && (!f.Name.Equals("SHAPE.len")) && (!f.Name.Equals("SHAPE.area")))
                {
                    DataColumn c = buildColumn(f);
                    colCollection.Add(c);
                }
            }
            return dataTable;
        }

        #endregion


        #region =========================== PUBLIC ===============================
        
        public DataTableBuilder(List<IField> fields)
        {
            this.fields = fields;
        }

        public DataTableBuilder(IFields fields)
        :this(GeneralConveror.ListOf(fields))
        {}

        public DataTableBuilder(List<String> wantedFields, List<IField> allFields)
            : this(GeneralConveror.ListOf(wantedFields, allFields)) { }

        public DataTableBuilder(IFeatureClass featureClass)
            : this(GeneralConveror.ListOf(featureClass.Fields))
        {}

        /// <summary>
        /// A property represents the DataTable after creation, to fill the table
        /// use DataTableAdapter
        /// </summary>
        public DataTable DataTable
        {
            get { return buildTable(); }
        }


        #endregion
    }
}
